<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Utils\CurlUtil;
use App\User;
use Illuminate\Support\Facades\DB;
class SyncUserInfoToApp extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:user_info_to_app';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步用户信息到app';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
//        $total = User::where('mobile','!=','')->where('app_user_id','')->count();
        $users = User::where('mobile','!=','')->where('app_user_id','')->take(100)->get();

        foreach($users as $user){
            DB::beginTransaction();
            try{
                $address = env('APP_INTERFACE_URL').'api/communityUser/userSynchronization';
                $data['mobile'] = $user->mobile;
                $data['nickname'] = mb_substr($user->nickname,0,20,'UTF-8');
                if(strpos($user->avatar,'http') !== false){
                    $data['avatar'] = $user->avatar;
                }else{
                    if($user->avatar == ''){
                        $data['avatar'] = '';
                    }else{
                        $data['avatar'] = env('IMG_URL').$user->avatar;
                    }
                }
                $data['sex'] = $user->sex;
                $data['unionid'] = $user->unionid;
                $data['registerTime'] = date('Y-m-d H:i:s',strtotime($user->created_at));

                if (empty($data)) {
                    return array("code"=>'200', "msg"=>"参数有误");
                }
//                logger()->info($data);
//                dd($data);
                $result = CurlUtil::appCurl($address,$data);
                $appInfo = [];
                if($result){
//                    logger()->info($result);
                    $appInfo = json_decode($result,true);
                }else{
                    DB::commit();
                    continue;
                }
                $app_user_id = $appInfo['app_user_id']?$appInfo['app_user_id']:0;
                $user->app_user_id = $app_user_id;
                $user->save();
                DB::commit();
//                dd($user);
            }catch(\Exception $e){
                logger()->info($e->getMessage());
                DB::rollback();
            }

        }

    }
}
